package com.xoa.controller.work;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.rms.RmsFileMapper;
import com.xoa.dao.rms.RmsRollMapper;
import com.xoa.dao.sms.SmsBodyMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.*;
import com.xoa.model.document.DocumentModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.flowRunFeedback.FlowRunFeedback;
import com.xoa.model.rms.RmsFileWithBLOBs;
import com.xoa.model.rms.RmsRollWithBLOBs;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.ThreadSerivice.ThreadService;
import com.xoa.service.WFE.WFEFactory.WFEFlowProcess;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.WFE.WFERunner.WFEFlowRun;
import com.xoa.service.WFE.WFERunner.WFEFlowRunPrcs;
import com.xoa.service.WFE.WFERunner.WFERunner;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.sys.SystemInfoService;
import com.xoa.service.syspara.SysParaService;
import com.xoa.service.work.WorkService;
import com.xoa.service.workflow.flowDestroy.FlowDestroy;
import com.xoa.service.workflow.flowUtil.FlowUtilService;
import com.xoa.service.workflow.flowtype.FlowRunPrcsService;
import com.xoa.service.workflow.reportSettings.FlowReportService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import com.xoa.util.ipUtil.IpAddr;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.net.InetAddress;


/**
 * 创建作者:   张龙飞
 * 创建日期:   2017年5月22日 上午11:43:13
 * 类介绍  :    新建工作
 * 构造参数:
 */
@Controller
@RequestMapping("/workflow/work")
@SuppressWarnings("all")
public class WorkController {

    @Autowired
    private FlowReportService flowReportService;

    @Autowired
    private FlowRunLogMapper flowRunLogMapper;

    @Autowired
    private WFELog wfeLog;

    @Resource
    private FlowRunPrcsService flowRunPrcsService;

    @Resource
    private WorkService workService;

    @Resource
    private SmsService smsService;

    @Resource
    private SysParaService sysParaService;

    @Resource
    private FlowRunMapper flowRunMapper;

    @Resource
    private SmsBodyMapper SmsBodyMapper;

    @Autowired
    protected WFERunner wfeRunner;

    @Autowired
    private SystemInfoService systemInfoService;
    @Resource
    private WFEFlowRun wfeFlowRun;

    @Resource
    private WFEFlowRunPrcs wfeFlowRunPrcs;

    @Resource
    private FlowRunPrcsMapper flowRunPrcsMapper;

    @Autowired
    private WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;

    @Autowired
    private WFEFlowProcess wfeFlowProcess;

    @Autowired
    private FlowProcessMapper flowProcessMapper;

    @Autowired
    private ThreadService threadService;

    @Resource
    private UsersMapper usersMapper;

    @Autowired
    private RmsRollMapper rmsRollMapper;

    @Autowired
    private DocumentSerivce documentSerivce;

    @Autowired
    protected EnclosureService enclosureService;

    @Autowired
    private FlowUtilService flowUtilService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RmsFileMapper rmsFileMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FlowTypeModelMapper flowTypeModelMapper;

    @Autowired
    private FlowFormTypeMapper flowFormTypeMapper;

    @Autowired
    protected WorkMapper workMapper;

    @Autowired
    protected FlowAssignMapper flowAssignMapper;

    @Autowired
    private ToBeReadMapper toBeReadMapper;

    @Autowired
    DocumentModelMapper documentModelMapper;

    @RequestMapping("addwork")
    public String work(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/add_work";
    }

    @RequestMapping("workformh5")
    public String workformh5(HttpServletRequest request, HttpSession session) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        try {
            Object locale = request.getSession().getAttribute("LOCALE_SESSION_ATTRIBUTE_NAME");
            String realPath = request.getSession().getServletContext().getRealPath("/");
            Map<String, String> map = systemInfoService.getSystemInfo(realPath, locale, request);
            if (map != null && map.size() > 0) {
                Iterator i = map.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    if (entry.getKey().equals("module")) {
                        session.setAttribute("module", entry.getValue());
                        break;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "app/workflow/work/workformh5";
    }

    @RequestMapping("limit")
    public String limit(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/limit";
    }

    @RequestMapping("zhuanjiaoh5")
    public String zhuanjiaoh5(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/zhuanjiaoh5";
    }
    @RequestMapping("workformh5PreView")
    public String workformh5PreView(HttpServletRequest request, HttpSession session) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        try {
            Object locale = request.getSession().getAttribute("LOCALE_SESSION_ATTRIBUTE_NAME");
            String realPath = request.getSession().getServletContext().getRealPath("/");
            Map<String, String> map = systemInfoService.getSystemInfo(realPath, locale, request);
            if (map != null && map.size() > 0) {
                Iterator i = map.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    if (entry.getKey().equals("module")) {
                        session.setAttribute("module", entry.getValue());
                        break;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "app/workflow/work/workformh5PreView";
    }

    @RequestMapping("turnh5")
    public String turnh5(HttpServletRequest request, HttpSession session) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        try {
            Object locale = request.getSession().getAttribute("LOCALE_SESSION_ATTRIBUTE_NAME");
            String realPath = request.getSession().getServletContext().getRealPath("/");
            Map<String, String> map = systemInfoService.getSystemInfo(realPath, locale, request);
            if (map != null && map.size() > 0) {
                Iterator i = map.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    if (entry.getKey().equals("module")) {
                        session.setAttribute("module", entry.getValue());
                        break;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "app/workflow/work/turnh5";
    }

    @RequestMapping("feedback")
    public String feedback(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/feedback";
    }

    @RequestMapping("newflowguider")
    public String addflowGuider(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/newFlowGuider";
    }

    @RequestMapping("workList")
    public String workList(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/workList";
    }

    @RequestMapping("workLists")
    public String workLists(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/workLists";
    }

    @RequestMapping("waitwork")
    public String waitwork(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/waitwork";
    }

    @RequestMapping("endwork")
    public String endwork(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/endwork";
    }

    @RequestMapping("allwork")
    public String allwork(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/allwork";
    }

    @RequestMapping("workform")
    public String workform(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/workform";
    }

    @RequestMapping("workformedit")
    public String workformedit(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/workformedit";
    }

    @RequestMapping("workform1")
    public String workform1(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/workform1";
    }

    @RequestMapping("workformPreView")
    public String workformPreView(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/workformPreView";
    }

    //瑞莱工作流查看详情
    @RequestMapping("workformAppPreView")
    public String workformAppPreView(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workapp/work/workformAppPreView";
    }

    @RequestMapping("notifyWork")
    public String notifyWork(HttpServletRequest request) {
        return "app/workflow/work/notifyWork";
    }

    @RequestMapping("workDelegate")
    public String workDelegate(HttpServletRequest request) {
        return "app/workflow/work/workDelegate";
    }

    //骆鹏添加2017/7/12
    @RequestMapping("/automaticNumbering")
    public String automaticNumbering() {
        return "app/workflow/work/automaticNumbering";
    }

    @RequestMapping("/automaticNumberingOne")
    public String automaticNumberingOne() {
        return "app/workflow/work/automaticNumberingOne";
    }

    @RequestMapping("/numberingAdminister")
    public String numberingAdminister() {
        return "app/workflow/work/numberingAdminister";
    }


    @RequestMapping("/businessApplications")
    public String businessApplications(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        if (!sysParaService.checkIsHaveSecure(user, 5)) {
            return "app/common/development";
        }
        return "app/workflow/work/businessApplications";
    }

    @RequestMapping("querySQL")
    public String querySQL(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/querySQL";
    }

    @RequestMapping("/switchWork")
    public String switchWork(HttpServletRequest request) {
        return "/app/workflow/work/add_workOther";
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月7日 上午10:31:07
     * 方法介绍:   快速新建
     * 参数说明:   @param request 请求
     * 参数说明:   @param flowId  流程id
     * 参数说明:   @param prcsId(flowStep)  步骤id对应flow_run_prcs的prcsId
     * 参数说明:   @param flowPrcs(prcsId)  流程实例步骤id对应flow_run_prcs的flowPrcs以及flow_procsee的prcsId
     * 参数说明             preView     应对查询
     * 参数说明:   @return
     *
     * @return ToJson<FlowFast>
     */
    @RequestMapping("workfastAdd")
    @ResponseBody
    public ToJson<FlowFast> fastAdd(HttpServletRequest request,
                                    Integer flowId,
                                    @RequestParam(value = "flowStep", required = false, defaultValue = "0") Integer prcsId,
                                    @RequestParam(value = "prcsId", required = false) String flowProcs,
                                    @RequestParam(value = "runId", required = false) String id,
                                    @RequestParam(value = "runName", required = false) String runName,
                                    @RequestParam(value = "preView", required = false) String preView
    ) {
        String tableName = request.getParameter("tableName");
        String tabId = request.getParameter("tabId");
        String userId = request.getParameter("userId");
        Users user = new Users();
        //解决工作监控代为转交
        if (StringUtils.checkNull(userId)) {
            // Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            //user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        } else {
            user = usersMapper.findUsersByuserId(userId);
        }
        String sqlType = ContextHolder.getConsumerType();
        if (!StringUtils.checkNull(flowProcs)) {
            threadService.addNewworkFastAdd(user, flowId, prcsId, flowProcs, id, tableName, tabId, sqlType);
        }

        return wfeRunner.getWfeFlowRunInfo().workFastAdd(user, flowId, prcsId, flowProcs, id, request, sqlType, runName, preView);
    }


    public ToJson<FlowFast> newFlow(Integer flowId,
                                    @RequestParam(value = "flowStep", required = false, defaultValue = "0") Integer prcsId,
                                    @RequestParam(value = "prcsId", required = false) String flowProcs,
                                    @RequestParam(value = "runId", required = false) String id,
                                    @RequestParam(value = "runName", required = false) String runName,
                                    @RequestParam(value = "preView", required = false) String preView
    ) {
        String tableName = request.getParameter("tableName");
        String tabId = request.getParameter("tabId");
        String userId = request.getParameter("userId");
        Users user = new Users();
        //解决工作监控代为转交
        if (StringUtils.checkNull(userId)) {
            // Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            //user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        } else {
            user = usersMapper.findUsersByuserId(userId);
        }
        String sqlType = ContextHolder.getConsumerType();
        if (!StringUtils.checkNull(flowProcs)) {
            threadService.addNewworkFastAdd(user, flowId, prcsId, flowProcs, id, tableName, tabId, sqlType);
        }

        return wfeRunner.getWfeFlowRunInfo().workFastAdd(user, flowId, prcsId, flowProcs, id, request, sqlType, runName, preView);
    }

    @RequestMapping("createGuide")
    @ResponseBody
    public AjaxJson createGuide(String flowId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().createGuide(flowId, user, request);
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月27日 上午9:54:09
     * 方法介绍:   转交保存表单数据
     * 参数说明:   @param flowId 流程id
     * 参数说明:   @param prcsId 流程实例步骤id
     * 参数说明:   @param flowPrcs 步骤id
     * 参数说明:   @param formdata 表单json串
     * 参数说明:   @param runId  flowRun的流程实例Id
     * 参数说明:   @param runName flowRun的流程实例名称
     * 参数说明:   @param beginTime flowRun流程实例创建时间
     * 参数说明:   @param beginUser  flowRun流程发起人Id
     * 参数说明:   @param formdata  表单上数据字段映射
     * 参数说明:   @param modifydata  表单上数据字段映射
     * 参数说明:   @param fromDataReject  表单的name和id
     * 参数说明:   @return
     *
     * @return ToJson<FlowFast>
     */
    @RequestMapping("nextwork")
    @ResponseBody
    public ToJson<FlowFast> nextwork(HttpServletRequest request,
                                     @RequestParam(value = "flowId", required = false) Integer flowId,
                                     @RequestParam(value = "formdata", required = false) String formdata,
                                     @RequestParam(value = "modifydata", required = false) String modifydata,
                                     @RequestParam(value = "formLength", required = false) String formlength,
                                     @RequestParam(value = "runId", required = false) int runId,
                                     @RequestParam(value = "runName", required = false) String runName,
                                     @RequestParam(value = "beginTime", required = false) String beginTime,
                                     @RequestParam(value = "beginUser", required = false) String beginUser,
                                     @RequestParam(value = "prcsId", required = false) String prcsId,
                                     @RequestParam(value = "fromDataReject", required = false) String fromDateReject,
                                     @RequestParam(value = "tableName", required = false) String tableName,
                                     @RequestParam(value = "tabId", required = false) String tabId,
                                     @RequestParam(value = "flowPrcs", required = false) String flowPrcs

    ) {
        String sqlType = ContextHolder.getConsumerType();

        if (StringUtils.checkNull((String) request.getSession().getAttribute(
                "loginDateSouse"))) {
            sqlType = "xoa1001";
        }
        //工作等级
      /*  String workLevel = request.getParameter("workLevel");
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("runId",runId);
        if (StringUtils.checkNull(workLevel)){
            map.put("workLevel",0);
        }else {
            map.put("workLevel",workLevel);
        }

        flowRunMapper.updateWorkLevel(map);*/
        return wfeRunner.getWfeFlowRunInfo().nextwork(flowId, formdata, modifydata, formlength, runId, runName, beginTime, beginUser, sqlType, prcsId, fromDateReject, tableName, tabId, flowPrcs, request);
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月7日 上午10:32:03
     * 方法介绍:   转交后保存
     * 参数说明:   @param request 请求
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param runName 流程实例名称
     * 参数说明:   @param flowId  流程id
     * 参数说明:   @param prcsId  当前流程实例步骤id
     * 参数说明:   @param prcsFlag  步骤状态
     * 参数说明:   @param flowPrcs  要转交的下一步骤流程设计id
     * 参数说明:   @param beginTime  流程实例创建时间
     * 参数说明:   @param beginUser 流程发起人id     并发  1，2
     * 参数说明:   @param jingbanUser  经办人         并发   1，2，3，|4，5，6
     * 参数说明:   @param currentPrcsId  当前流程设计步骤id
     * 参数说明:   @param flowStep  当前流程实例步骤id
     * 参数说明:   @return
     *
     * @return ToJson<FlowRunPrcs>
     */
    @RequestMapping("saveWorkcs")
    @ResponseBody
    public ToJson<FlowRunPrcs> saveworkcs(HttpServletRequest request,
                                          @RequestParam(value = "runId", required = false) String runId,
                                          @RequestParam(value = "runName", required = false) String runName,
                                          @RequestParam(value = "flowId", required = false) String flowId,
                                          @RequestParam(value = "prcsId", required = false) String prcsId,
                                          @RequestParam(value = "prcsflag", required = false) String prcsFlag,
                                          @RequestParam(value = "flowPrcs", required = false) String flowPrcs,
                                          @RequestParam(value = "beginTime", required = false) String beginTime,
                                          @RequestParam(value = "beginUser", required = false) String beginUser,
                                          @RequestParam(value = "jingbanUser", required = false) String jingbanUser,
                                          @RequestParam(value = "currentPrcsId", required = false) String currentPrcsId,
                                          @RequestParam(value = "orgAdd", required = false) String orgadd,
                                          @RequestParam(value = "viewUser", required = false) String viewUser,
                                          @RequestParam(value = "smsContent", required = false) String smsContent,
                                          @RequestParam(value = "smsType", required = false) String smsType,
                                          @RequestParam(value = "tableName", required = false) String tableName,
                                          @RequestParam(value = "tabId", required = false) String tabId,
                                          @RequestParam(value = "flowStep", required = false) String flowStep

    ) {
        String tuisong = request.getParameter("tuisong");
        String topDefault = request.getParameter("topDefault");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        //经办人数组
        String[] alljingbanArray = jingbanUser.split("\\|");
        String[] jingbanArray = null;
        //用来判断发送事务提醒
        int num = 0;
        FlowProcess flowProcess = null;
        //下一步经办步骤
        String[] fpArray = flowPrcs.split(",");
        String branchCount = "";
        if (fpArray.length > 1) {
            branchCount = flowPrcs;
        }
        flowProcess = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(currentPrcsId));
        if (fpArray.length == 1) {//如果不是并发
            if (!"0".equals(flowPrcs)) {
                //查询下一步步骤是否是强制合并
                FlowProcess flowProcess1 = wfeFlowProcess.findbyprcsId(Integer.parseInt(flowId), Integer.parseInt(flowPrcs));
                //如果是强制合并节点
                if ("1".equals(flowProcess1.getGatherNode())) {
                    Map map = new HashMap();
                    map.put("runId", runId);
                    map.put("prcsId", prcsId);
                    //查询该步骤是否是并发步骤
                    List<FlowRunPrcs> flowRunPrcsList = wfeFlowRunPrcs.findByRunId1(map);
                    if (flowRunPrcsList.size() > 0) {
                        //规避设置允许并发，但没有走并发分支
                        if (!StringUtils.checkNull(flowRunPrcsList.get(0).getBranchCount())) {
                            List listPrcs = new ArrayList(); //存储强制合并节点的步骤号
                            //求出能到强制合并节点的步骤号
                            Map maps = new HashMap();
                            maps.put("flowId", flowProcess1.getFlowId());
                            maps.put("prcsTo", flowProcess1.getPrcsId());
                            String prcsIdStr = wfeFlowProcess.findFlowIdPrcsId(maps);
                            String[] prcsIdArray = null;
                            if (!StringUtils.checkNull(prcsIdStr)) {
                                prcsIdArray = prcsIdStr.split(",");
                                for (String s : prcsIdArray) {
                                    if (!s.equals(currentPrcsId)) {//去除本步骤查询
                                        listPrcs.add(s);
                                    }
                                }
                            }
                            //统计flow——run——prcs这些步骤号prcs_flag状态为(1,2) 是否为1条  为一条 则发送事务提醒
                            Map<String, Object> m = new HashMap<String, Object>();
                            m.put("runId", runId);
                            m.put("listPrcs", listPrcs);
                            List<Integer> listFlag = new ArrayList<Integer>();
                            listFlag.add(1);
                            listFlag.add(2);
                            m.put("listFlag", listFlag);
                            Integer checkBranchCount = wfeFlowRunPrcs.checkBranchCount(m);
                            if (checkBranchCount == null) {
                                workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId, runName, flowId, prcsId, currentPrcsId, tabId, topDefault, smsContent, request, smsType, user, orgadd, jingbanUser, viewUser);
                            }
                        }
                    }
                } else {
                    //发送事务提醒
                    workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId, runName, flowId, prcsId, currentPrcsId, tabId, topDefault, smsContent, request, smsType, user, orgadd, jingbanUser, viewUser);
                }
            } else {
                workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId, runName, flowId, prcsId, currentPrcsId, tabId, topDefault, smsContent, request, smsType, user, orgadd, jingbanUser, viewUser);
            }
        } else { //如果是并发节点发送事务提醒
            //发送事务提醒
            workService.todoWorkSmsBoby(beginUser, flowPrcs, tableName, runId, runName, flowId, prcsId, currentPrcsId, tabId, topDefault, smsContent, request, smsType, user, orgadd, jingbanUser, viewUser);
        }

        //主办人提交消除事物提醒（结束流程时没有主办人）
        //String[] strs1 = flowPrcs.split(",");
        String smsUrl = null;
        if ("2".equals(flowProcess.getTopDefault())) {
            smsUrl = "/workflow/work/workform?opflag=0&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        } else {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        }
        if ("document".equals(tableName)) {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + flowStep + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + currentPrcsId + "&isNomalType=false";
            smsService.updatequerySmsByType("70", user.getUserId(), smsUrl.trim());
        } else if ("budget".equals(tableName)) {
            smsUrl += "&tableName=budget";
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        } else {
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        }

        //return wfeRunner.getWfeFlowRunInfo().savework11(Integer.parseInt(runId), runName, Integer.parseInt(prcsId), flowStep, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, Integer.parseInt(currentPrcsId), topDefault, tabId, tableName);



        return wfeRunner.getWfeFlowRunInfo().saveworkyuan(runId, runName, flowId, prcsId, prcsFlag, flowStep, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, branchCount);
    }



    @RequestMapping("saveWork")
    @ResponseBody
    public ToJson<FlowRunPrcs> savework(HttpServletRequest request,
                                        @RequestParam(value = "runId", required = false) Integer runId,
                                        @RequestParam(value = "runName", required = false) String runName,
                                        @RequestParam(value = "flowId", required = false) Integer flowId,
                                        @RequestParam(value = "prcsId", required = false) Integer prcsId,
                                        @RequestParam(value = "prcsflag", required = false) String prcsFlag,
                                        @RequestParam(value = "flowPrcs", required = false) String flowPrcs,
                                        @RequestParam(value = "beginTime", required = false) String beginTime,
                                        @RequestParam(value = "beginUser", required = false) String beginUser,
                                        @RequestParam(value = "jingbanUser", required = false) String jingbanUser,
                                        @RequestParam(value = "currentPrcsId", required = false) Integer currentPrcsId,
                                        @RequestParam(value = "orgAdd", required = false) String orgadd,
                                        @RequestParam(value = "viewUser", required = false) String viewUser,
                                        @RequestParam(value = "smsContent", required = false) String smsContent,
                                        @RequestParam(value = "smsType", required = false) String smsType,
                                        @RequestParam(value = "tableName", required = false) String tableName,
                                        @RequestParam(value = "tabId", required = false) String tabId,
                                        @RequestParam(value = "flowStep", required = false) String flowStep,
                                        String htmlContent

    ) {
        System.out.println("新建工作");

        if(StringUtils.checkNull(flowPrcs)){
            ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
            toJson.setFlag(1);
            return toJson;
        }
        String tuisong = request.getParameter("tuisong");
        String topDefault = request.getParameter("topDefault");
        String userId = request.getParameter("userId");
        Users user = null;
        //解决工作监控代为转交
        if (StringUtils.checkNull(userId)) {
            // Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            //user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        } else {
            user = usersMapper.findUsersByuserId(userId);
        }

        //经办人数组
        String[] alljingbanArray = jingbanUser.split("\\|");
        String[] jingbanArray = null;
        String branchCount = null;
        //用来判断发送事务提醒
        FlowProcess   flowProcess = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);

        //主办人提交消除事物提醒（结束流程时没有主办人）
        //String[] strs1 = flowPrcs.split(",");
        String smsUrl = null;
        if ("2".equals(flowProcess.getTopDefault())) {
            smsUrl = "/workflow/work/workform?opflag=0&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        } else {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        }
        if ("document".equals(tableName)) {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + flowStep + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + currentPrcsId + "&isNomalType=false";
            smsService.updatequerySmsByType("70", user.getUserId(), smsUrl.trim());
        } else if ("budget".equals(tableName)) {
            smsUrl += "&tableName=budget";
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        } else {
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        }
        //获取当前步骤是否需要进行自动归档
        FlowRun flowRun = wfeFlowRun.find(runId);  //获取当前流程信息  runId
        FlowProcess  flowPro = flowProcessMapper.findbyprcsIds(flowId, currentPrcsId);
        String autoArchiveSet = flowPro.getAutoArchiveSet();
        if(!StringUtils.checkNull(autoArchiveSet)){
            File(autoArchiveSet,runId,flowRun,flowPro,htmlContent);
        }
        if (!StringUtils.checkNull(runId+"")&&!StringUtils.checkNull(prcsId+"")){
            flowAssignMapper.updateStatusFlowAssign(runId,prcsId);
        }
        if(Integer.valueOf(prcsId)==1){
            //修改创建时的日期
            Map<String,Object> mapDocument=new HashMap<>();
            mapDocument.put("runId",runId);
            mapDocument.put("createTime",new Date());
            documentModelMapper.updateByRunId(mapDocument);
        }

        return wfeRunner.getWfeFlowRunInfo().savework(runId, runName, prcsId, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, tableName,smsContent,smsType,orgadd);

        //return wfeRunner.getWfeFlowRunInfo().savework(runId, runName, flowId, prcsId, prcsFlag, flowStep, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, branchCount);
    }


    public void File(String autoArchiveSet,Integer runId,FlowRun flowRun,FlowProcess flowPro,String htmlContent){   //归档
        String file = JSONArray.parseObject(autoArchiveSet).getString("file");
        String rmsRollRoom = JSONArray.parseObject(autoArchiveSet).getString("rmsRollRoom");
        String rmsRoll = JSONArray.parseObject(autoArchiveSet).getString("rmsRoll");
        String fileRule = JSONArray.parseObject(autoArchiveSet).getString("fileRule");//是否强制归档（0不强制归档，1强制归档
        String mappingRule = JSONArray.parseObject(autoArchiveSet).getString("mappingRule");//归档字段映射规则
        String fileContent = JSONArray.parseObject(autoArchiveSet).getString("fileContent");//fileContent 归档内容（0正文，1附件，2表单，3三者压缩包

        //当前年月
        String ym = new SimpleDateFormat("yyyy").format(new Date());
        String sqlType = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
        if ("1".equals(file)){   //判断是否归档
            if (!StringUtils.checkNull(rmsRollRoom)&&!StringUtils.checkNull(rmsRoll)){   //判断是否选择卷库，案卷
                if ("1".equals(fileRule)){   //是否强制归档（0不强制归档，1强制归档
                    RmsRollWithBLOBs oldRmsRoll = rmsRollMapper.selectByPrimaryKey(Integer.parseInt(rmsRoll));
                    oldRmsRoll.setRollId(null);
                    oldRmsRoll.setRollName(oldRmsRoll.getRollName()+ym);//新案卷的名字为老案卷加当前系统的年份
                    oldRmsRoll.setAddTime(new Date());
                    List<RmsRollWithBLOBs> i = rmsRollMapper.selectName(oldRmsRoll.getRollName(), oldRmsRoll.getRoomId());//查询当前卷库下有没有相同名的 案卷
                    if (i.size()==0){  //没有相同名的 案卷 新建
                        rmsRollMapper.insertSelectives(oldRmsRoll);
                    }else {
                        oldRmsRoll = i.get(0);
                    }

                    //为防止并发 新写一个插入方法 案卷

                    RmsFileWithBLOBs rmsFile = new RmsFileWithBLOBs();//新建一个文件类
                    rmsFile.setRollId(oldRmsRoll.getRollId());//设置新建的案卷
                    rmsFile.setSendDate(new Date());//发文时间
                    rmsFile.setSecret("1");
                    rmsFile.setUrgency("1");
                    rmsFile.setFileKind("1");
                    rmsFile.setFileType("1");

                    rmsFile.setAttachmentId("");//防止出现null情况
                    rmsFile.setAttachmentName("");

                    rmsFile.setAttachmentId2("");//公文  //防止出现null情况
                    rmsFile.setAttachmentName2("");

                    rmsFile.setRunId(runId);//设置当前流程id
                    rmsFile.setFileTitle(flowRun.getRunName()+ym);


                    try {
                        if (fileContent.contains("0")){

                            List<Attachment> fathAttach = new ArrayList<Attachment>();//先设置空的正文
                            FileUploadUtil fileUploadUtil = new FileUploadUtil();
                            //获取父公文实体类
                            DocumentModel fathDocument = documentSerivce.checkRunId(runId);
                            //获取父公文的正文
                            if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//判断api为空
                                fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainFileName(), fathDocument.getMainFile(), sqlType, "document");
                            }else {
                                fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainAipFileName(), fathDocument.getMainAipFile(), sqlType, "document");
                            }
                            //复制文件
                            List<Attachment> sonAttach = fileUploadUtil.copyFile(fathAttach, sqlType, "document");
                            for (Attachment attachment : sonAttach) {
                                enclosureService.saveAttachment(attachment);
                            }
                            Object[] o = FileUploadUtil.reAttachment(sonAttach);   //返回附件信息
                            rmsFile.setAttachmentId2(o[0].toString());
                            rmsFile.setAttachmentName2(o[1].toString());
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    if (fileContent.contains("1")){   //附件
                        if (!StringUtils.checkNull(rmsFile.getAttachmentId())) {    //进行附件复制
                            FileUploadUtil fileUploadUtil = new FileUploadUtil();
                            List<Attachment> fathAttach = new ArrayList<Attachment>();
                            fathAttach = GetAttachmentListUtil.returnAttachment(flowRun.getAttachmentName(), flowRun.getAttachmentId(), sqlType, "workFlow");
                            List<Attachment> sonAttach = fileUploadUtil.copyFile(fathAttach, sqlType, "workFlow");
                            for (Attachment attachment : sonAttach) {
                                enclosureService.saveAttachment(attachment);
                            }
                            Object[] o = FileUploadUtil.reAttachmentAll(sonAttach);
                            rmsFile.setAttachmentId(o[0].toString());
                            rmsFile.setAttachmentName(o[1].toString());
                        }
                    }
                    if (fileContent.contains("2")){    //复制表单

                        FileUploadUtil fileUploadUtil = new FileUploadUtil();

                        ToJson<Attachment> attachmentToJson = flowUtilService.htmlFormTOPDF(request,response,runId,GetAttachmentListUtil.MODULE_ROLL_MANAGE,htmlContent);
                        List<Attachment> fathAttach = new ArrayList<Attachment>();
                        fathAttach = GetAttachmentListUtil.returnAttachment(attachmentToJson.getObj1().toString().split("%")[1], attachmentToJson.getObj1().toString().split("%")[0], sqlType, "document");

                        List<Attachment> sonAttach = fileUploadUtil.copyFile(fathAttach, sqlType, "workFlow");
                        for (Attachment attachment : sonAttach) {
                            enclosureService.saveAttachment(attachment);
                        }
                        Object[] o = FileUploadUtil.reAttachment(sonAttach);
                        rmsFile.setAttachmentId(rmsFile.getAttachmentId()+o[0].toString());
                        rmsFile.setAttachmentName(rmsFile.getAttachmentName()+o[1].toString());

                    }
                    if (fileContent.contains("3")){   //三者压缩
                        if (!StringUtils.checkNull(rmsFile.getAttachmentId())){
                            //ToJson<Attachment> attachmentToJson = flowUtilService.htmlFormTOPDF(request,response,runId,GetAttachmentListUtil.MODULE_ROLL_MANAGE,htmlContent);
                            //rmsFile.setAttachmentId(rmsFile.getAttachmentId()+attachmentToJson.getObj().get(0).getAttachId());
                            //rmsFile.setAttachmentName(rmsFile.getAttachmentName()+attachmentToJson.getObj().get(0).getAttachName());
                        }
                    }
                    rmsFileMapper.insertSelective(rmsFile);

                    //进行字段映射
                    if (!StringUtils.checkNull(mappingRule)){
                        try {
                            mapping(flowPro,rmsFile,mappingRule,flowRun);
                        }catch (Exception e){

                        }
                    }
                }else {   //不强制归档
                    RmsRollWithBLOBs oldRmsRoll = rmsRollMapper.selectByPrimaryKey(Integer.parseInt(rmsRoll));

                    RmsFileWithBLOBs rmsFile = new RmsFileWithBLOBs();//新建一个文件类
                    rmsFile.setRollId(oldRmsRoll.getRollId());//设置新建的案卷
                    rmsFile.setSendDate(new Date());//发文时间
                    rmsFile.setSecret("1");
                    rmsFile.setUrgency("1");
                    rmsFile.setFileKind("1");
                    rmsFile.setFileType("1");

                    rmsFile.setAttachmentId("");//防止出现null情况
                    rmsFile.setAttachmentName("");

                    rmsFile.setAttachmentId2("");//公文  //防止出现null情况
                    rmsFile.setAttachmentName2("");

                    rmsFile.setRunId(runId);//设置当前流程id
                    rmsFile.setFileTitle(flowRun.getRunName()+ym);

                    try {
                        if (fileContent.contains("0")){
                            List<Attachment> fathAttach = new ArrayList<Attachment>();//先设置空的正文
                            FileUploadUtil fileUploadUtil = new FileUploadUtil();
                            //获取父公文实体类
                            DocumentModel fathDocument = documentSerivce.checkRunId(runId);
                            //获取父公文的正文
                            if (StringUtils.checkNull(fathDocument.getMainAipFile())) {//判断api为空
                                fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainFileName(), fathDocument.getMainFile(), sqlType, "document");
                            }else {
                                fathAttach = GetAttachmentListUtil.returnAttachment(fathDocument.getMainAipFileName(), fathDocument.getMainAipFile(), sqlType, "document");
                            }
                            //复制文件
                            List<Attachment> sonAttach = fileUploadUtil.copyFile(fathAttach, sqlType, "document");
                            for (Attachment attachment : sonAttach) {
                                enclosureService.saveAttachment(attachment);
                            }
                            Object[] o = FileUploadUtil.reAttachment(sonAttach);   //返回附件信息
                            rmsFile.setAttachmentId2(o[0].toString());
                            rmsFile.setAttachmentName2(o[1].toString());
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    if (fileContent.contains("1")){
                        if (!StringUtils.checkNull(rmsFile.getAttachmentId())){    //进行附件复制

                            FileUploadUtil fileUploadUtil = new FileUploadUtil();
                            List<Attachment> fathAttach = new ArrayList<Attachment>();
                            fathAttach = GetAttachmentListUtil.returnAttachment(flowRun.getAttachmentName(),flowRun.getAttachmentId(),sqlType,"workFlow");
                            List<Attachment> sonAttach = fileUploadUtil.copyFile(fathAttach, sqlType, "workFlow");
                            for (Attachment attachment : sonAttach) {
                                enclosureService.saveAttachment(attachment);
                            }
                            Object[] o = FileUploadUtil.reAttachmentAll(sonAttach);
                            rmsFile.setAttachmentId(o[0].toString());
                            rmsFile.setAttachmentName(o[1].toString());
                        }
                    }
                    if (fileContent.contains("2")){   //复制表单
                        //正文转为附件   不为空   进行附件复制
                        FileUploadUtil fileUploadUtil = new FileUploadUtil();

                        ToJson<Attachment> attachmentToJson = flowUtilService.htmlFormTOPDF(request,response,runId,GetAttachmentListUtil.MODULE_ROLL_MANAGE,htmlContent);
                        List<Attachment> fathAttach = new ArrayList<Attachment>();
                        fathAttach = GetAttachmentListUtil.returnAttachment(attachmentToJson.getObj1().toString().split("%")[1], attachmentToJson.getObj1().toString().split("%")[0], sqlType, "document");

                        List<Attachment> sonAttach = fileUploadUtil.copyFile(fathAttach, sqlType, "workFlow");
                        for (Attachment attachment : sonAttach) {
                            enclosureService.saveAttachment(attachment);
                        }
                        Object[] o = FileUploadUtil.reAttachment(sonAttach);
                        //ToJson<Attachment> attachmentToJson = flowUtilService.htmlFormTOPDF(request,response,runId,GetAttachmentListUtil.MODULE_ROLL_MANAGE,htmlContent);
                        rmsFile.setAttachmentId(rmsFile.getAttachmentId()+o[0].toString());
                        rmsFile.setAttachmentName(rmsFile.getAttachmentName()+o[1].toString());

                    }
                    if (fileContent.contains("3")){   //三者压缩包
                        if (!StringUtils.checkNull(rmsFile.getAttachmentId())){//正文转为附件   不为空   进行附件复制
                                /*ToJson<Attachment> attachmentToJson = flowUtilService.htmlFormTOPDF(request,response,runId,GetAttachmentListUtil.MODULE_ROLL_MANAGE,htmlContent);
                                rmsFile.setAttachmentId(rmsFile.getAttachmentId()+attachmentToJson.getObj().get(0).getAttachId());
                                rmsFile.setAttachmentName(rmsFile.getAttachmentName()+attachmentToJson.getObj().get(0).getAttachName());*/
                        }
                    }
                    rmsFileMapper.insertSelective(rmsFile);

                    //进行字段映射
                    if (!StringUtils.checkNull(mappingRule)){
                        try {
                            mapping(flowPro,rmsFile,mappingRule,flowRun);
                        }catch (Exception e){

                        }
                    }
                }
            }

        }
    }

    public void mapping(FlowProcess flowPro,RmsFileWithBLOBs rmsFile,String mappingRule,FlowRun flowRun) {
        //头表单
        Document headDoc = null;
        Document endDoc = null;

        Map<String, Document> documentMap = null;
        documentMap = flowMapping(flowRun);

        headDoc = documentMap.get("headDocument");

        String relation = mappingRule;//映射分割
        String[] mappingArray = relation.split(",");
        List<String> key = new ArrayList<>();
        List<String> value = new ArrayList<>();
        for (String mapping : mappingArray) {
            String[] mappingHeadAndEnd = mapping.split("=>");
            if (mappingHeadAndEnd.length > 1) {
                String mappingHead = mappingHeadAndEnd[0];//映射头
                String mappingEnd = mappingHeadAndEnd[1];//映射尾
                String headData = HtmlUtil.getDocumentName(headDoc, mappingHead);
                //String endData = HtmlUtil.getDocumentName(endDoc, mappingEnd);
                if (headData != null && !headData.trim().equals("")) {
                    /*if (endData != null && !endData.trim().equals("")) {

                        //value.add(endData);
                    }*/
                    value.add(mappingEnd);
                    key.add(headData);
                }

            }

        }
        List<String> values = new ArrayList<>();
        if (key.size() > 0) {
            Map<String, Object> valueMap = workMapper.getDataValue(key, flowRun.getRunId(), "flow_data_" + flowRun.getFlowId());
            if (valueMap != null) {
                for (String k : key) {
                    Object v = valueMap.get(k);
                    if (v != null) {
                        values.add(String.valueOf(v));
                    } else {
                        values.add("");
                    }
                }
            }
        }
        for (int i=0;i<key.size();i++){
            if ("文件号".equals(value.get(i))){
                rmsFile.setFileCode(values.get(i));
            }
            if ("文件标题".equals(value.get(i))){
                rmsFile.setFileTitle(values.get(i));
            }
            if ("文件主题词".equals(value.get(i))){
                rmsFile.setFileSubject(values.get(i));
            }
            if ("文件辅标题".equals(value.get(i))){
                rmsFile.setFileTitle0(values.get(i));
            }
            if ("文件页数".equals(value.get(i))){
                rmsFile.setFilePage(values.get(i));
            }
            if ("打印页数".equals(value.get(i))){
                rmsFile.setPrintPage(values.get(i));
            }
            if ("备注".equals(value.get(i))){
                rmsFile.setRemark(values.get(i));
            }
        }
        rmsFileMapper.updateByPrimaryKeySelective(rmsFile);
    }

    public Map<String, Document> flowMapping(FlowRun headFlowRun) {
        //查询头数据表单
        Integer headFlowId = headFlowRun.getFlowId();
        FlowTypeModel headFlowType = flowTypeModelMapper.queryOneObject(headFlowId);
        FlowFormType headFlowForm = flowFormTypeMapper.qureyItemMax(headFlowType.getFormId());
        //获得具体的表单数据  头表单
        String headPrintModel = headFlowForm.getPrintModel();
        //解析表单 头表单
        Document headDocument = getField(headPrintModel);

        Map<String, Document> documentMap = new HashMap<>();
        documentMap.put("headDocument", headDocument);

        return documentMap;
    }

    public Document getField(String printModel) {
        Document document = null;
        //解析html
        document = Jsoup.parse(printModel);
        return document;
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月3日 上午9:54:09
     * 方法介绍:   查询表单数据
     * 参数说明:   @param request 请求
     * 参数说明:   @param flowId 流程id
     * 参数说明:   @param runId  flowRun的流程实例Id
     * 参数说明:   @return
     *
     * @return Map<String, Object>
     */
    @RequestMapping("selectFlowData")
    @ResponseBody
    public Map<String, Object> fastAdd(HttpServletRequest request,
                                       @RequestParam(value = "runId", required = false) Integer runId,
                                       @RequestParam(value = "flowId", required = false) Integer flowId
    ) {
        return wfeRunner.getWfeFlowRunInfo().fastAdd(runId, flowId, request);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月26日 上午9:54:09
     * 方法介绍:   公共附件上传
     * 参数说明:   @param files 上传的文件
     * 参数说明:   @param fmodule 模块名
     * 参数说明:   @param request  请求
     * 参数说明:   @return
     *
     * @return ToJson<Attachment>
     */
    @RequestMapping(value = "workUpload", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    public void workUpload(@RequestParam(value = "file", required = false) MultipartFile[] files, String module, String runId,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        String company = ContextHolder.getConsumerType();
        String flowPrcs = request.getParameter("flowPrcs");
        if (StringUtils.checkNull(company) || company.contains("null")) {
            company = "xoa1001";
        }
        ToJson<Attachment> toJson = wfeRunner.getWfeFlowRunInfo().workUpload(files, company, module, runId, flowPrcs, request);
        response.setHeader("content-type", "text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = response.getOutputStream();
        OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");

        ow.write(JSONObject.toJSONString(toJson));
        ow.flush();
        ow.close();
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月28日 上午9:54:09
     * 方法介绍:   查找公共附件
     * 参数说明:   @param runId 流程实例Id
     * 参数说明:   @return
     *
     * @return ToJson<Attachment>
     */
    @RequestMapping(value = "findworkUpload", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public ToJson<Attachment> findworkUpload(HttpServletRequest request, String runId) {
        String company = ContextHolder.getConsumerType();
        if (StringUtils.checkNull(company) || company.contains("null")) {
            company = "xoa1001";
        }
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
        return wfeRunner.getWfeFlowRunInfo().findworkUpload(runId, company);
    }

    /**
     * 创建作者:
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   保存会签意见
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param content 会签内容
     * 参数说明:   @param prcsId  流程实例步骤id
     * 参数说明:   @param flowPrcs  步骤id
     * 参数说明:   @param file  附件
     * 参数说明:   @return
     *
     * @return ToJson<FlowRunFeedback>
     */
    @RequestMapping(value = "workfeedback", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public ToJson<FlowRunFeedback> workfeedback(String content, String runId, String prcsId, String flowPrcs, String feedFlag,
                                                HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
        return wfeRunner.getWfeFlowRunInfo().workfeedback(content, runId, prcsId, flowPrcs, userId, feedFlag);
    }

    /**
     * 增加会签人提醒会签人会签
     * 王禹萌
     * 2018-08-07 14：24
     *
     * @param runId   流水号
     * @param prcsId  实际步骤
     * @param userId  加签人userId
     * @param flowId  流程ID
     * @param runName 流程名字
     * @return 事务提醒
     */
    @RequestMapping(value = "addFeedback", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public ToJson<SmsBody> addFeedback(HttpServletRequest request, Integer runId, Integer prcsId, String flowPrcs, String userId, Integer flowId, String runName, String topFlag) {
        return wfeRunner.getWfeFlowRunInfo().addFeedback(request, runId, prcsId, flowPrcs, userId, flowId, runName, topFlag);
    }

    /**
     * 查询加签人为经办人接口
     * 王禹萌
     * 2018-08-10 10：33
     *
     * @param runId
     * @param prcsId
     * @param flowPrcs
     * @return
     */
    @RequestMapping(value = "getFlowRunPrecsUser", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public BaseWrappers getFlowRunPrecsUser(String runId, Integer prcsId, Integer flowPrcs) {
        return wfeRunner.getWfeFlowRunInfo().getFlowRunPrecsUser(runId, prcsId, flowPrcs);
    }


    /**
     * 创建作者:
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   查询会签意见
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param prcsId  流程实例步骤id
     * 参数说明:   @param flowPrcs  步骤id
     * 参数说明:   @return
     *
     * @return ToJson<FlowRunPrcs>
     */
    @RequestMapping(value = "findworkfeedback", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxJson findworkfeedback(HttpServletRequest request, String runId, String prcsId, String flowPrcs, String signlock) {
        String company = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
        return wfeRunner.getWfeFlowRunInfo().findworkfeedback(runId, prcsId, flowPrcs, userId, company, signlock);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   查询分支
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param flowId  流程实例步骤id
     * 参数说明:   @param flowPrcs  步骤id
     * 参数说明:   @return
     *
     * @return ToJson<FlowFast>
     */
    @RequestMapping(value = "findbranch", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson findBranch(HttpServletRequest request, String flowId, String runId, String flowPrcs, String search, String deptNo) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        String currentFlowPrcs = request.getParameter("currentFlowPrcs");
        return wfeRunner.getWfeFlowRunInfo().findBranch(flowId, runId, flowPrcs, currentFlowPrcs, user, search, deptNo);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年4月30日 上午9:52:22
     * 方法介绍:   删除工作流附件
     * 参数说明    @param runid 流程实例id
     * 参数说明:   @param aid 附件主键
     * 参数说明:   @param module 模块
     * 参数说明:   @param ym 年月
     * 参数说明:   @param attachmentId 附件id
     * 参数说明:   @param attachmenrName 附件名字
     * 参数说明:   @param company 公司
     * 参数说明:   @param response 响应
     * 参数说明:   @param request 请求
     * 参数说明:   @return
     */
    @RequestMapping(value = "deletework", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public ToJson delete(String runId,
                         @RequestParam("AID") String aid,
                         @RequestParam("MODULE") String module,
                         @RequestParam("YM") String ym,
                         @RequestParam("ATTACHMENT_ID") String attachmentId,
                         @RequestParam("ATTACHMENT_NAME") String attachmentName,
                         @RequestParam("COMPANY") String company,
                         HttpServletResponse response,
                         HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunInfo().delete(runId, aid, module, ym, attachmentId, attachmentName, company, response, request);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   查询回退之前步骤
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param allowBack  回退状态
     * 参数说明:   @param prcsId  步骤id
     * 参数说明:   @return
     *
     * @return ToJson<FlowFast>
     */
    @RequestMapping(value = "getflowprcsdata", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public ToJson<FlowRunPrcs> getflowprcsdata(String allowBack, String runId, String prcsId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().getflowprcsdata(allowBack, runId, prcsId, user.getUserId());
    }

    /**
     * 工作监控退回接口
     * 王禹萌
     * 2018-07-26
     *
     * @param allowBack
     * @param runId
     * @param prcsId
     * @param request
     * @return
     */
    @RequestMapping(value = "queryflowprcsdata", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public ToJson<FlowRunPrcs> queryflowprcsdata(String allowBack, String runId, String prcsId, String userId, HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunInfo().getflowprcsdata(allowBack, runId, prcsId, userId);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   回退步骤插入
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param  回退流程步骤id
     * 参数说明:   @param prcsId  当前流程实例步骤id
     * 参数说明:   @param flowStep  当前流程步骤id
     * 参数说明:   @return
     *
     * @return
     */
    @RequestMapping(value = "insertprcsdata", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxJson insertprcsdata(Integer id,Integer backId,
                                   String feedback, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().insertprcsdata(id,backId,user,feedback);
    }

    /**
     * 工作监控退回
     * 王禹萌
     * 2018-07-26 19：58
     *
     * @param runId
     * @param flowStep
     * @param prcsId
     * @param flowPrcs
     * @param feedback
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping(value = "workInsertprcsdata", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson workInsertprcsdata(String runId, String flowStep, String prcsId, String flowPrcs, String feedback, String userId, HttpServletRequest request) {
        Users user = usersMapper.findUsersByuserId(userId);
        return wfeRunner.getWfeFlowRunInfo().insertprcsdata(runId, flowStep, prcsId, flowPrcs, user, feedback);
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/24 20:29
     * 方法介绍:   查询待办工作
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "selectWork", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson<FlowRunPrcs> selectObject(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                                     @RequestParam(value = "page", required = false) Integer page,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                     @RequestParam(value = "useFlag", required = false) boolean useFlag

    ) {
        String flowId = request.getParameter("flowId");
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        if (!StringUtils.checkNull(flowId)) {
            maps.put("flowId", flowId);
        }
        return wfeRunner.getWfeFlowRunPrcs().selectObject(maps, page, pageSize, useFlag);
    }

    /**
     * 创建作者: 刘建
     * 创建日期: 2020-06-29 14:59
     * 方法介绍: 查询代办工作/公文
     * @param flowRunPrcs
     * @param request
     * @param page
     * @param pageSize
     * @param useFlag
     * @return com.xoa.util.ToJson<com.xoa.model.workflow.FlowRunPrcs>
     */
    @RequestMapping(value = "selectWorkDocument", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson<FlowRunPrcs> selectWorkDocument(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                                           @RequestParam(value = "page", required = false) Integer page,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                           @RequestParam(value = "useFlag", required = false) boolean useFlag) {
        String flowId = request.getParameter("flowId");
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        if (!StringUtils.checkNull(flowId)) {
            maps.put("flowId", flowId);
        }
        return wfeRunner.getWfeFlowRunPrcs().selectWorkDocument(maps, page, pageSize, useFlag);
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/24 20:29
     * 方法介绍:   查询办结工作
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "selectEndWord", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    ToJson<FlowRunPrcs> selectEnd(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                                  @RequestParam(value = "page", required = false) Integer page,
                                  @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  @RequestParam(value = "useFlag", required = false) boolean useFlag
    ) {
        ContextHolder.setConsumerType("xoa" + (String) request.
                getSession().getAttribute(
                "loginDateSouse"));
        String flowId = request.getParameter("flowId");
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        if (!StringUtils.checkNull(flowId)) {
            maps.put("flowId", flowId);
        }
        if (!StringUtils.checkNull(flowRunPrcs.getBeginTime())) {
            maps.put("beginTime", flowRunPrcs.getBeginTime());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getEndTime())) {
            maps.put("endTime", flowRunPrcs.getEndTime());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getState())) {
            maps.put("state", flowRunPrcs.getState());
        }
        return wfeRunner.getWfeFlowRunPrcs().selectEnd(maps, page, pageSize, useFlag);
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/24 20:29
     * 方法介绍:   查询挂起工作
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "selectHang", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    ToJson<FlowRunPrcs> selectEndHang(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                                      @RequestParam(value = "page", required = false) Integer page,
                                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                      @RequestParam(value = "useFlag", required = false) boolean useFlag) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        return wfeRunner.getWfeFlowRunPrcs().selectHang(maps, page, pageSize, useFlag);
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/5/24 20:29
     * 方法介绍:   查询所有工作
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "selectAll", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    ToJson<FlowRunPrcs> selectAll(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                                  @RequestParam(value = "page", required = false) Integer page,
                                  @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  @RequestParam(value = "useFlag", required = false) boolean useFlag
    ) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        String flowId = request.getParameter("flowId");
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        if (!StringUtils.checkNull(flowId)) {
            maps.put("flowId", flowId);
        }
        return wfeRunner.getWfeFlowRunPrcs().selectAll(maps, page, pageSize, useFlag);
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/20 13:59
     * 方法介绍:   删除流程根据ID
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "deleteRunPrcs", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson<FlowRunPrcs> deleteRunPrcs(FlowRunPrcs flowRunPrcs, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            flowRunPrcs.setUserId(userId);
        }
        return wfeRunner.getWfeFlowRunPrcs().deleteRunPrcs(flowRunPrcs);
    }


    /**
     * 创建作者:
     * 创建日期:   2018/6/7 13:59
     * 方法介绍:   根据ID 批量删除
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "deleteRunPrcsBatch", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    ToJson<FlowRunPrcs> deleteRunPrcsBatch(String idBatch, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return wfeRunner.getWfeFlowRunPrcs().deleteRunPrcsBatch(idBatch);
    }


//    /**
//     * 创建作者:   张勇
//     * 创建日期:   2017/6/1 11:40
//     * 方法介绍:  根据runId查询关联办理人的步骤和所在部门
//     * 参数说明:
//     * @return
//     */
//    @RequestMapping(value = "findAllNode", produces = {"application/json;charset=UTF-8"},method = RequestMethod.GET)
//    public @ResponseBody
//    ToJson<FlowRunPrcs> findAllNode(HttpServletRequest request,
//                                  @RequestParam(value = "runId", required = false) Integer runId) {
//        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute(
//                "loginDateSouse"));
//        return flowRunPrcsService.findAllNode(runId);
//    }

    @RequestMapping("procseeDesign")
    public String procseeDesign(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/procseeDesign";
    }

    @RequestMapping("processSpeak")
    public String processSpeak(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/workflow/work/processSpeak";
    }


    @RequestMapping("exportFlowRun")
    @ResponseBody
    public ToJson<FlowFast> exportFlowRun(HttpServletRequest request,
                                          Integer flowId,
                                          @RequestParam(value = "flowStep", required = false) Integer prcsId,
                                          @RequestParam(value = "prcsId", required = false) String flowProcs,
                                          @RequestParam(value = "runId", required = false) String id,
                                          @RequestParam(value = "runName", required = false) String runName
    ) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");

        return wfeRunner.getWfeFlowRunInfo().workFastAdd(user, flowId, prcsId, flowProcs, id, request, sqlType, runName, null);
    }


    @RequestMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        //定义导出工作列表，1：待办，2：办结，3：全部,4：委托工作
        String type = request.getParameter("type");
        wfeRunner.getWfeFlowRunInfo().exportExcel(user, type, response,request);
    }

    /**
     * 创建作者:   季佳伟
     * 创建日期:   2017/8/23 16:50
     * 方法介绍:   根据前台传入的runId,prcsId,toId,flowPrcs,opFlag,从session中获取users
     * 参数说明:
     *
     * @return
     */
    @RequestMapping("/entrust")
    @ResponseBody
    public ToJson<FlowRunPrcs> entrust(String runId, String prcsId, String toId,
                                       String flowPrcs, String opFlag, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().entrust(runId, prcsId, toId, flowPrcs, opFlag, user);
    }

    /**
     * 获取所有委托工作
     */
    @RequestMapping(value = "entrustWork", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    AjaxJson entrustWork(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                         @RequestParam(value = "page", required = false) Integer page,
                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                         @RequestParam(value = "useFlag", required = false) boolean useFlag

    ) {
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        return wfeRunner.getWfeFlowRunPrcs().entrustWork(maps, page, pageSize, useFlag);
    }

    /**
     * 工作监控
     */
    @RequestMapping(value = "monitoring", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxJson monitoring(
            @RequestParam(value = "runName", required = false) String runName,
            @RequestParam(value = "runId", required = false) Integer runId,
            @RequestParam(value = "flowName", required = false) String flowName,
            @RequestParam(value = "workLevel", required = false) String workLevel,
            @RequestParam(value = "userId", required = false) String userId,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "flowId", required = false) String flowId,
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "useFlag", required = false) boolean useFlag,
            @RequestParam(value = "output", required = false) String output,
            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> maps = new HashMap<String, Object>();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        maps.put("runName", runName);
        maps.put("runId", runId);
        maps.put("flowName", flowName);
        maps.put("workLevel", workLevel);
        maps.put("user", user);
        if (!StringUtils.checkNull(userId) && userId.contains(",")) {
            maps.put("userId", userId.substring(0, userId.length() - 1));
        } else {
            maps.put("userId", userId);
        }
        maps.put("status", status);
        maps.put("flowId", flowId);
        maps.put("currentUid", user.getUid());
        return wfeRunner.getWfeFlowRunPrcs().monitoring(maps, page, pageSize, useFlag, output, request, response);
    }


    @RequestMapping("workMonitoring")
    public String workMonitoring(HttpServletRequest request) {
        return "app/workflow/work/workMonitor";
    }

    //添加关注
    @RequestMapping("workAttention")
    @ResponseBody
    public AjaxJson workAttention(HttpServletRequest request,
                                  @RequestParam(value = "runId", required = false) Integer runId,
                                  @RequestParam(value = "userId", required = false) String userId,
                                  @RequestParam(value = "status", required = false) String status) {
        return wfeRunner.getWfeFlowRunInfo().workAttention(runId, userId, status);
    }


    //工作结束和工作删除,状态值0为工作结束1为工作删除
    @RequestMapping("worDelete")
    @ResponseBody
    public AjaxJson worDelete(HttpServletRequest request,
                              @RequestParam(value = "runId", required = false) Integer runId,
                              @RequestParam(value = "status", required = false) String status) {
        return wfeRunner.getWfeFlowRunInfo().worDelete(runId, status);
    }


    /**
     * 创建作者:
     * 会签保存
     */
    @RequestMapping("saveHandle")
    @ResponseBody
    public AjaxJson saveHandle(HttpServletRequest request,
                               @RequestParam(value = "runId", required = false) Integer runId,
                               @RequestParam(value = "prcsId", required = false) Integer prcsId,
                               @RequestParam(value = "flowPrcs", required = false) String flowPrcs

    ) {
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        String flowId = request.getParameter("flowId");
        String tableName = request.getParameter("tableName");
        String tabId = request.getParameter("tabId");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        threadService.add0pflagNewWorkFastAdd(user, Integer.parseInt(flowId), prcsId, flowPrcs, String.valueOf(runId), tableName, tabId, sqlType);
        return wfeRunner.getWfeFlowRunInfo().saveHandle(runId, prcsId, flowPrcs, user);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017/6/20 13:52
     * 方法介绍:   流程委托
     * 参数说明:
     *
     * @return
     */
    //run_id:1776,
    // prcs_key_id:3175,
    // prcs_id:2,
    // flow_prcs:3,
    // to_user:zhaomin, 委托给谁
    // from_user_name:lijia, 谁委托
    // op_flag:0
    //affair 事物提醒
    //message 短信提醒
    //context 发送的内容
    @RequestMapping("entrustUser")
    @ResponseBody
    public ToJson<FlowRunPrcs> entrust(FlowRunPrcs flowRunPrcs, String entrstUser, String affair, String message, String context, HttpServletRequest request) {
        return flowRunPrcsService.entrust(flowRunPrcs, entrstUser, affair, message, context, request);
    }

    /**
     * 创建作者:   zlf
     * 创建日期:   2018/1/18
     * 方法介绍:   结束时间\工作等级\工作删除状态修改
     * 参数说明:	   @param endTime 结束时间
     * 参数说明:	   @param delFlag  删除状态标志 0或1
     * 参数说明:	   @param workLevel  工作等级
     * 参数说明：      flag 1-删除工作 2-结束工作
     */
    @RequestMapping("updateState")
    @ResponseBody
    public ToJson<Object> updateState(HttpServletRequest request, String flag, String runId,
                                      @RequestParam(value = "prcsId", required = false) String prcsId,
                                      @RequestParam(value = "userId", required = false) String userId,
                                      @RequestParam(value = "flowPrcs", required = false) String flowPrcs,
                                      @RequestParam(value = "prcsFlag", required = false) String prcsFlag,
                                      @RequestParam(value = "flowId", required = false) String flowId
    ) {
        ToJson<Object> tojson = new ToJson<>(1, "error");
        try {
            int count = 0;
            Map<String, Object> map = new HashMap();
            //添加工作流使用日志--删除
            FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
            flowRunLog.setRunId(Integer.parseInt(runId));
            if ("1".equals(flag)) {//删除
                //map.put("endTime", DateFormat.getStrDate(new Date()));
                map.put("delFlag", 1);
                map.put("runId", runId);
                map.put("delTime", DateFormat.getStrDate(new Date()));
                count += wfeFlowRun.updateState(map);
                Map<String, String> smsMap = new HashMap<>();
                smsMap.put("prcsId", prcsId);
                smsMap.put("flowId", flowId);
                smsService.querySmsByTypeUpdateRunId("7", runId, smsMap);
                //插入日志
                flowRunLog.setType(Constant.TYPE10);

                wfeLog.addFlowRunLog(flowRunLog);
            } else {//结束

                String[] runIdArr = runId.split(",");
                for (int i = 0; i < runIdArr.length; i++) {
                    map.put("runId", runIdArr[i]);
                    map.put("prcsFlag", "4");
                    map.put("deliverTime", DateFormat.getStrDate(new Date()));
                    map.put("endTime", DateFormat.getStrDate(new Date()));
                    count += wfeFlowRunPrcs.updateEnd(map);

                    //装配日志对象
                    flowRunLog.setType(Constant.TYPE12);
                    //插入日志
                    wfeLog.addFlowRunLog(flowRunLog);
                }

            }
            if (count > 0) {
                tojson.setFlag(0);
                tojson.setMsg("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tojson;
    }

    /**
     * 创建作者:   王禹萌
     * 创建日期:   2018/6/21
     * 方法介绍:   结束时间\工作等级\批量工作删除状态修改
     * 参数说明:	   @param endTime 结束时间
     * 参数说明:	   @param delFlag  删除状态标志 0或1
     * 参数说明:	   @param
     * Level  工作等级
     */
    @RequestMapping("batchUpdateState")
    @ResponseBody
    public ToJson<Object> batchUpdateState(HttpServletRequest request, String runId ,String flag
    ) {
        ToJson<Object> tojson = new ToJson<>(1, "error");
        try {
            String[] idArray = runId.split(",");
            Map<String, Object> map = new HashMap();
            if (idArray != null && idArray.length > 0) {
                if("1".equals(flag)){
                    int count = 0;
                    // map.put("endTime", DateFormat.getStrDate(new Date()));
                    map.put("delFlag", 1);
                    map.put("runId", idArray);
                    map.put("delTime", DateFormat.getStrDate(new Date()));
                    count += wfeFlowRun.batchUpdateState(map);
                    smsService.querySmsByTypeBathchUpdateRunId("7", idArray);
                    if (count > 0) {
                        tojson.setFlag(0);
                        tojson.setMsg("ok");

                        /**    lr   工作流使用日志添加  多条删除操作  **/
                        FlowRunLog flowRunLog= wfeLog.getFlowRunLogByRequest(request);
                        flowRunLog.setType(Constant.TYPE10);
                        for (int i=0;i<idArray.length;i++){
                            flowRunLog.setRunId(Integer.parseInt(idArray[i]));
                            wfeLog.addFlowRunLog(flowRunLog);
                        }
                    }
                } else {
                    for (int i = 0; i < idArray.length; i++) {
                        map.put("runId", idArray[i]);
                        map.put("prcsFlag", "4");
                        map.put("deliverTime", DateFormat.getStrDate(new Date()));
                        map.put("endTime", DateFormat.getStrDate(new Date()));
                        wfeFlowRunPrcs.updateEnd(map);

                        FlowRunLog flowRunLog= wfeLog.getFlowRunLogByRequest(request);
                        //装配日志对象
                        flowRunLog.setType(Constant.TYPE12);
                        //插入日志
                        wfeLog.addFlowRunLog(flowRunLog);
                    }
                    tojson.setFlag(0);
                    tojson.setMsg("ok");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tojson;
    }

    /**
     * 创建作者:   牛江
     * 创建日期:   2018/1/18
     * 方法介绍:    催办
     * 参数说明:	   @param endTime 结束时间
     * 参数说明:	   @param delFlag  删除状态标志 0或1
     * 参数说明:	   @param workLevel  工作等级
     * 参数说明：      flag 1-删除工作 2-结束工作
     */
    @RequestMapping("reminders")
    @ResponseBody
    public ToJson<Object> reminders(Integer id, String userId, String flowPrcs, String runId, String runName, String flowId, String prcsId, String smsContent, HttpServletRequest request) {

        ToJson<Object> tojson = new ToJson<>(1, "error");
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            List<FlowRunPrcs> flowRunPrcsList = wfeFlowRunPrcsMapper.findMaxFrp(Integer.parseInt(runId));
            FlowRunPrcs flowRunPrcs = flowRunPrcsList.get(0);
            flowRunPrcs.setIsRemind(1);
            String content = "流水号：" + runId + "，工作名称/文号：" + runName;
            String remindUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + (flowRunPrcsList.get(0).getPrcsId()) + "&runId=" + runId;
            SmsBody smsBody = new SmsBody(user.getUserId(), "7", DateFormat.getTime(DateFormat.getCurrentTime()), remindUrl, smsContent);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("remindUrl", remindUrl);
            map.put("smsType", smsBody.getSmsType());
            map.put("bodyId", smsBody.getBodyId());
            List<SmsBody> smsBodyList = SmsBodyMapper.selSmsBody(map);
            //可能是新建的工作也能是已经催办过的流程
            if (smsBodyList.size() > 0) {
            /*    smsBody.setBodyId(smsBodyList.get(0).getBodyId());
                smsBody.setRemindFlag(smsBodyList.get(0).getRemindFlag());
                Map<String,Object> map1=new HashMap<>();
                map1.put("smsType",smsBody.getSmsType());
                map1.put("bodyId",smsBody.getBodyId());
                map1.put("remindFlag",smsBody.getRemindFlag());
                int a = SmsBodyMapper.selSmsSmsBody(map1);
                if(a>0){
                    tojson.setObj1(1);
                }*/
                //根据类型与时间更新到该流程的数据中
                Map<String, Object> map1 = new HashMap<>();
                map1.put("smsType", smsBodyList.get(0).getSmsType());
                map1.put("bodyId", smsBodyList.get(0).getBodyId());
                map1.put("smsContent", smsContent);
                map1.put("sendTime", DateFormat.getTime(DateFormat.getCurrentTime()));
                int i = SmsBodyMapper.updateSmsBody(map1);// 更新
                System.out.println(i);
            } else { //第一次点击（未读）
                workService.todoWorkSmsBoby(flowRunPrcs.getUserId(), flowRunPrcs.getFlowPrcs().toString(), null, runId, runName, flowId, String.valueOf(flowRunPrcs.getPrcsId()), null, null, null, smsContent, request, "7", user, null, flowRunPrcs.getUserId(), "");

            }

            if (StringUtils.checkNull(flowRunPrcs.getDeliverTime())) {
                flowRunPrcs.setDeliverTime("2000-01-01 00:00:00");
            }
            int count = flowRunPrcsMapper.upPrcsById(flowRunPrcs);
            if (count > 0) {
                tojson.setFlag(0);
                tojson.setMsg("ok");

                /**** 工作流使用添加日志-- 催办  ****/
                FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
                //装配日志对象
                flowRunLog.setRunId(Integer.parseInt(runId));
                flowRunLog.setType(Constant.TYPE16);
                if (prcsId != null) {
                    flowRunLog.setPrcsId(Integer.parseInt(prcsId));
                }
                if (flowId != null) {
                    flowRunLog.setFlowId(Integer.parseInt(flowId));
                }
                if (flowPrcs != null) {
                    flowRunLog.setFlowPrcs(Integer.parseInt(flowPrcs));
                }

                flowRunLog.setTransactor(flowRunLogMapper.selectUserName(flowRunPrcs.getUserId()));
                //添加日志
                wfeLog.addFlowRunLog(flowRunLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tojson;
    }


    /**
     * 创建作者:   牛江丽
     * 创建日期:   2018/1/22 13:52
     * 方法介绍:   恢复执行
     * 参数说明：
     *
     * @return
     */
    @RequestMapping("resumeExe")
    @ResponseBody
    public ToJson resumeExe(String runId, Integer id) {

        return wfeFlowRunPrcs.resumeExe(runId, id);
    }


    //工作撤回
    @RequestMapping("workBack")
    @ResponseBody
    public AjaxJson workBack(Integer prcsId, Integer flowPrcs, String runId, String userId, String tabId, String tableName) {
        return wfeFlowRunPrcs.workBack(prcsId, flowPrcs, runId, userId, tabId, tableName);
    }

    //提醒指定步骤经办人
    @RequestMapping("remindSteps")
    @ResponseBody
    public AjaxJson remindSteps(Integer prcsId, String runId) {
        return wfeFlowRunPrcs.remindSteps(prcsId, runId);
    }


    //H5微应用
    //新建工作
    @RequestMapping("/workflowAddh5")
    public String workflowAdd() {
        return "/app/workflow/m/addh5";
    }

    //工作流首页
    @RequestMapping("/workflowIndexh5")
    public String workflowIndex() {
        return "/app/workflow/m/indexh5";
    }

    //new工作流
    @RequestMapping("/workflowNewWorkh5")
    public String workflowNewWork() {
        return "/app/workflow/m/new_workh5";
    }

    //我发起的
    @RequestMapping("/workflowLaunchh5")
    public String workflowLaunch() {
        return "/app/workflow/m/launchh5";
    }

    //工作流详情
    @RequestMapping("/workformh5m")
    public String workform() {
        return "/app/workflow/m/workformh5";
    }

    @Autowired
    private FlowDestroy flowDestroy;

    /**
     * 创建作者： 李然
     * 方法作用：工作流销毁模糊查询
     *
     * @param request
     * @param runName
     * @param flowId
     * @param runId
     * @param beginTime
     * @param endTime
     * @param beginUser
     * @param pageSize
     * @param page
     * @param useFlag
     * @return
     */
    @RequestMapping("/workDestroy/query")
    @ResponseBody
    public ToJson toQuery(HttpServletRequest request,
                          @RequestParam(required = false) Integer flowId,
                          @RequestParam(required = false) Integer runId,
                          @RequestParam(required = false) String runName,
                          @RequestParam(required = false) String beginTime,
                          @RequestParam(required = false) String endTime,
                          @RequestParam(required = false) String beginUser,
                          @RequestParam(required = false) Integer pageSize,
                          @RequestParam(required = false) Integer page,
                          @RequestParam(required = false) Boolean useFlag) {

        if (endTime != null) {
            if (endTime.equals("")) {
                endTime = null;
            }
        }
        if (beginTime != null) {
            if (beginTime.equals("")) {
                beginTime = null;
            }
        }
        //将参数传入map中
        Map maps = new HashMap();
        maps.put("runName", runName);
        maps.put("flowId", flowId);
        maps.put("runId", runId);
        maps.put("beginTime", beginTime);
        maps.put("endTime", endTime);
        maps.put("beginUser", beginUser);
        //分页
        PageParams pages = new PageParams();
        pages.setPage(page);
        pages.setPageSize(pageSize);
        pages.setUseFlag(true);
        maps.put("page", pages);
        //获得tojson对象
        ToJson toJson = new ToJson();
        //获得查询结果
        List<FlowRun> flowRunList = flowDestroy.query(maps);
        List<FlowRun> flowRuns = new ArrayList();
        if (flowRunList != null) {
            for (FlowRun flowRun : flowRunList) {
                //拼接附件
                String attachmentId = flowRun.getAttachmentId();
                String attachmentName = flowRun.getAttachmentName();
                String sqlType = "xoa" + (String) request.getSession().getAttribute(
                        "loginDateSouse");
                List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(attachmentName, attachmentId, sqlType, GetAttachmentListUtil.MODULE_WORKFLOW);
                //存储到对象中
                flowRun.setAttachments(attachments);
                //取出时间字符串的.0
                String delDateString = org.apache.commons.lang3.StringUtils.substringBefore(flowRun.getDelTime(), ".");
                flowRun.setDelTime(delDateString);
                //存储对象到list中
                flowRuns.add(flowRun);
            }
            //传递
            toJson.setMsg("ok");
            toJson.setObj(flowRuns);
            toJson.setFlag(0);
            toJson.setTotleNum(pages.getTotal());
        } else {
            toJson.setMsg("null");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：点击销毁按钮或全部销毁进行销毁数据
     * @创建时间：9:41 2018/7/5
     * allDestroy参数接受全部删除按钮传过来的参数，1为全部删除
     **/
    @RequestMapping("/workDestroy")
    @ResponseBody
    public ToJson workDestroy(HttpServletRequest request,
                              @RequestParam(value = "allDestroy", required = false) Integer allDestroy,
                              @RequestParam(value = "runIdArray[]", required = false) @RequestBody String[] runIdArray
    ) {
        ToJson toJson = new ToJson();
        String result = "sha ye mei you";//数据回显
        int count = 0;//返回的影响行数
        //只需放入request将自动装配User，装配Ip。返回添加日志所需的对象参数
        FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
        //装配添加日志所需属性，必填
        flowRunLog.setType(Constant.TYPE13);
        //如果全部删除
        if (allDestroy != null && allDestroy == 1) {
            count = flowDestroy.allDestroy();
            if (count != 0) {//判断销毁行数是否为0，不为0代表操作成功
                toJson.setFlag(0);
                toJson.setMsg("ok");
                //如果手动设置日志信息content将优先执行手动的
                flowRunLog.setContent("执行全部销毁操作");
                //插入日志
                wfeLog.addFlowRunLog(flowRunLog);
            } else {
                toJson.setMsg("null");
            }
        } else {//如果没执行全部操作将根据数组删除
            //判断数组是否为空
            if (runIdArray != null) {
                //通过runId获得flowId集合
                List<Integer> flowIdArrays = flowDestroy.getFlowIdByrunIdArryInt(runIdArray);
                //拼接表名
                String tableName = "flow_data_";
                String[] tableNamesStr = new String[flowIdArrays.size()];
                for (int j = 0; j < flowIdArrays.size(); j++) {
                    tableNamesStr[j] = (tableName + flowIdArrays.get(j));
                }
                for (int n = 0; n < tableNamesStr.length; n++) {
                    //循环删除表
                    count = count + flowDestroy.destroyFlowDataNum(runIdArray[n], tableNamesStr[n]);
                }
                try {
                    //循环添加销毁日志
                    for (int i = 0; i < runIdArray.length; i++) {
                        Integer runId = Integer.parseInt(runIdArray[i]);
                        flowRunLog.setRunId(runId);
                        wfeLog.addFlowRunLog(flowRunLog);
                    }
                    //删除flowrun表的
                    count = count + flowDestroy.destroyFlowRunByRunIdArray(runIdArray);
                    count = count + flowDestroy.destroyFlowRunPrcsByRunIdArray(runIdArray);
                    StringBuffer stringBuffer=new StringBuffer();
                    List<Integer> list=new ArrayList<>();
                    for (String s:runIdArray){
                        list.add(Integer.parseInt(s));
                    }
                    flowAssignMapper.deleteFlowAssign(list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (count != 0) {
                    toJson.setMsg("ok");
                    toJson.setFlag(0);
                } else {
                    toJson.setMsg("修改失败");
                }
            }
        }

        return toJson;
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：还原功能
     * @创建时间：9:57 2018/7/5
     * allRestore参数接受全部还原按钮传过来的参数，1为全部还原
     **/
    @RequestMapping("/workRestore")
    @ResponseBody
    public ToJson workRestore(HttpServletRequest request,
                              @RequestParam(value = "allRestore", required = false) Integer allRestore,
                              @RequestParam(value = "runIdArray[]", required = false) String[] runIdArray
    ) {
        ToJson toJson = new ToJson();
        String result = "sha ye mei you";//数据回显
        int count = 0;//返回的影响行数
        FlowRunLog flowRunLog = wfeLog.getFlowRunLogByRequest(request);
        flowRunLog.setType(Constant.TYPE14);
        if (allRestore != null && allRestore == 1) {
            count = flowDestroy.allRestore();
            toJson.setFlag(0);
            flowRunLog.setContent("执行全部还原操作");
            wfeLog.addFlowRunLog(flowRunLog);
        } else {
            //否则如果数组不为空
            if (runIdArray != null) {
                count = count + flowDestroy.restoreFlowRunByRunIdArray(runIdArray);
                if (count != 0) {
                    toJson.setMsg("ok");
                    toJson.setFlag(0);
                    for (int i = 0; i < runIdArray.length; i++) {
                        Integer runId = Integer.parseInt(runIdArray[i]);
                        flowRunLog.setRunId(runId);
                        wfeLog.addFlowRunLog(flowRunLog);
                    }
                } else {
                    toJson.setMsg("null");
                }
            }
        }
        return toJson;
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月27日 上午9:54:09
     * 方法介绍:   转交保存表单数据
     * 参数说明:   @param flowId 流程id
     * 参数说明:   @param prcsId 流程实例步骤id
     * 参数说明:   @param flowPrcs 步骤id
     * 参数说明:   @param formdata 表单json串
     * 参数说明:   @param runId  flowRun的流程实例Id
     * 参数说明:   @param runName flowRun的流程实例名称
     * 参数说明:   @param beginTime flowRun流程实例创建时间
     * 参数说明:   @param beginUser  flowRun流程发起人Id
     * 参数说明:   @return
     *
     * @return ToJson<FlowFast>
     */
    @RequestMapping("editWorkfrom")
    @ResponseBody
    public AjaxJson editWorkfrom(HttpServletRequest request,
                                 @RequestParam(value = "flowId", required = false) String flowId,
                                 @RequestParam(value = "formdata", required = false) String formdata,
                                 @RequestParam(value = "runId", required = false) Integer runId,
                                 @RequestParam(value = "runName", required = false) String runName

    ) {
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        if (StringUtils.checkNull((String) request.getSession().getAttribute(
                "loginDateSouse"))) {
            sqlType = "xoa1001";
        }
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

        return wfeRunner.getWfeFlowRunInfo().editWorkfrom(flowId, formdata, runId, runName, sqlType, user);
    }


    //前往报表映射
    @RequestMapping("/flowReportMain")
    public String flowReportMain() {
        return "app/workflow/report/index";
    }

    /**
     * 李然
     *
     * @param request 获取当前用户，根据用户userId来查询有没有此用户管理的报表
     * @return
     */
    @RequestMapping("/getReportList")
    @ResponseBody
    public ToJson getReportList(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return flowReportService.getReportList(user.getUserId());
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：根据主键人rid获取一条记录
     * @创建时间：16:29 2018/7/30
     **/
    @RequestMapping("/getReportById")
    @ResponseBody
    public ToJson getReportById(@RequestParam("rid") Integer rid) {
        return flowReportService.getReportById(rid);
    }


    /**
     * @param flowId    表单名字拼接
     * @param beginTime 起始时间
     * @param endTime   终止时间
     * @param deptIds   部门id串
     * @param rid       唯一主键
     * @param definds   自定义条件串
     * @param type      是否为导出
     * @return
     * @创建作者:李然 Lr
     * @方法描述：多条件查询报表
     * @创建时间：10:51 2018/7/31
     */

    @RequestMapping("/queryReport")
    @ResponseBody
    public ToJson queryReport(@RequestParam(required = false) String flowId,
                              @RequestParam(required = false) String beginTime,
                              @RequestParam(required = false) String endTime,
                              @RequestParam(required = false) String deptIds,
                              @RequestParam(required = false) String userPrivs,
                              @RequestParam(required = false) Integer rid,
                              @RequestParam(required = false) String definds,
                              @RequestParam(required = false) Integer type,
                              HttpServletResponse response) {

        return flowReportService.queryReport(flowId, beginTime, endTime, deptIds, userPrivs, rid, definds, type, response);
    }

    //通过report id映射页面
    @RequestMapping("/flowReportByIdMain")
    public String flowReportByIdMain() {
        return "app/workflow/report/showReport";
    }

    @RequestMapping("/workDestruction")
    public String workDestruction() {
        return "/app/workflow/work/workDestruction";
    }

    @RequestMapping("/flowDiaryQuery")
    public String flowDiaryQuery() {
        return "/app/workflow/work/flowDiaryQuery";
    }

    @RequestMapping("/theProcessLog")
    public String theProcessLog() {
        return "/app/workflow/work/theProcessLog";
    }

    @RequestMapping("/DiaryIndex")
    public String DiaryIndex() {
        return "/app/workflow/work/DiaryIndex";
    }

    /**
     * 流程关联查询(我的工作-关联)
     * 王禹萌
     * 2018-08-27 18:02
     *
     * @param flowId
     * @return
     */
    @RequestMapping("/queryFlowAssociationSet")
    @ResponseBody
    public ToJson<FlowRunPrcs> queryFlowAssociationSet(Integer flowId) {
        return flowRunPrcsService.queryFlowAssociationSet(flowId);
    }


    /**
     * 创建作者:
     * 创建日期:   2017年6月27日 上午10:32:03
     * 方法介绍:   查询每个人会签意见最后一条
     * 参数说明:   @param runId  流程实例Id
     * 参数说明:   @param content 会签内容
     * 参数说明:   @param prcsId  流程实例步骤id
     * 参数说明:   @param flowPrcs  步骤id
     * 参数说明:   @param file  附件
     * 参数说明:   @return
     *
     * @return ToJson<FlowRunFeedback>
     */
    @RequestMapping(value = "findFinalfeedback", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxJson findFinalfeedback(Integer runId,
                                      HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunInfo().findFinalfeedback(runId);
    }

    /**
     * 表单历史数据回填
     *
     * @param flowId 流程id号
     * @param itemId 查询字段
     * @return
     */
    @RequestMapping(value = "getHistoryFlowRunDatas")
    @ResponseBody
    public AjaxJson getHistoryFlowRunDatas(Integer flowId,Integer runId,
                                           String itemId,String searchValue) {
        return wfeRunner.getWfeFlowRunInfo().getHistoryFlowRunDatas(flowId, runId,itemId,searchValue);
    }

    /**
     * 工作流选人获取所有可选人员
     *
     * @param request
     * @param flowId     流程编号
     * @param flowPrcs   步骤号
     * @param deptId     部门id（用以接收按部门选人参数）
     * @param userPriv   角色编号（用以接收按角色选人参数）
     * @param pageParams 分页插件
     * @return
     */
    @RequestMapping(value = "getWorkFlowUser", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxJson getWorkFlowUser(HttpServletRequest request,
                                    Integer flowId,
                                    Integer flowPrcs,
                                    Integer deptId,
                                    Integer userPriv,
                                    String deptNo,
                                    String search,
                                    PageParams pageParams) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().getWorkFlowUser(flowId, flowPrcs, user, deptId, userPriv, deptNo, search, pageParams);
    }

    /**
     * 获取流程转交时可以选择的分支
     *
     * @param request
     * @param flowId          流程号
     * @param currentFlowPrcs 当前流程设计器步骤好
     * @param runId           流水号
     * @return
     */
    @RequestMapping(value = "getBranch", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxJson getBranch(HttpServletRequest request,
                              @RequestParam Integer flowId,
                              @RequestParam Integer currentFlowPrcs,
                              @RequestParam Integer runId) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().getBranch(flowId, currentFlowPrcs, runId, user);
    }

    @RequestMapping(value ="signControl")
    @ResponseBody
    public AjaxJson signControl(Integer runId, Integer flowId,String signdata){
        return wfeRunner.getWfeFlowRunInfo().signControl(runId,flowId,signdata);
    }



    /**
     * @创建作者:李然 Lr
     * @方法描述：委托工作映射
     * @创建时间：19:27 2019/5/19
     **/
    @RequestMapping("entrustWorkMap")
    public String entrustWorkMap() {
        return "app/workflow/work/entrustWork";
    }

    //获取当前登陆人所有的委托工作
    @RequestMapping("/entrustWorkList")
    @ResponseBody
    public ToJson<FlowRunPrcs> entrustWorkList(HttpServletRequest request, PageParams pageParams) {
        return wfeRunner.getWfeFlowRunPrcs().entrustWorkList(request, pageParams);
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：收回委托
     * @创建时间：19:27 2019/5/19
     **/
    @RequestMapping("/backEntrustWork")
    @ResponseBody
    public ToJson backEntrustWork(HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunPrcs().backEntrustWork(request);
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：获取当前父流程或子流程
     * @创建时间：9:54 2019/6/13
     **/
    @RequestMapping("/prentAndSonFlow")
    @ResponseBody
    public ToJson prentAndSonFlow(HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunPrcs().prentAndSonFlow(request);
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：返回父流程人员
     * @创建时间：10:41 2019/6/13
     **/
    @RequestMapping("/returnPrentFlowUser")
    @ResponseBody
    public ToJson returnPrentFlowUser(HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunPrcs().returnPrentFlowUser(request);
    }


    /**
     * @创建作者:李然 Lr
     * @方法描述：结束子流程并返回父流程
     * @创建时间：10:42 2019/6/25
     **/
    @RequestMapping("/finishSonReturnParent")
    @ResponseBody
    public ToJson finishSonReturnParent(HttpServletRequest request) {
        return wfeRunner.getWfeFlowRunInfo().finishSonReturnParent(request);
    }


    @RequestMapping(value = "getWFBack")
    @ResponseBody
    public AjaxJson getWFBack(Integer flowId, Integer runId, Integer prcsId, Integer flowPrcs,HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return wfeRunner.getWfeFlowRunInfo().getWFBack(flowId, runId, prcsId,flowPrcs, user.getUserId());
    }

    /**
     *
     * @方法描述：重写的saveWork方法。定时任务自动保存转交的方法，方法不能出现request,需要的值必须得传
     *
     **/
    @RequestMapping("saveWorks")
    @ResponseBody
    public ToJson<FlowRunPrcs> saveworks(
            @RequestParam(value = "runId", required = false) Integer runId,
            @RequestParam(value = "runName", required = false) String runName,
            @RequestParam(value = "flowId", required = false) Integer flowId,
            @RequestParam(value = "prcsId", required = false) Integer prcsId,
            @RequestParam(value = "prcsflag", required = false) String prcsFlag,
            @RequestParam(value = "flowPrcs", required = false) String flowPrcs,
            @RequestParam(value = "beginTime", required = false) String beginTime,
            @RequestParam(value = "beginUser", required = false) String beginUser,
            @RequestParam(value = "jingbanUser", required = false) String jingbanUser,
            @RequestParam(value = "currentPrcsId", required = false) Integer currentPrcsId,
            @RequestParam(value = "orgAdd", required = false) String orgadd,
            @RequestParam(value = "viewUser", required = false) String viewUser,
            @RequestParam(value = "smsContent", required = false) String smsContent,
            @RequestParam(value = "smsType", required = false) String smsType,
            @RequestParam(value = "tableName", required = false) String tableName,
            @RequestParam(value = "tabId", required = false) String tabId,
            @RequestParam(value = "flowStep", required = false) String flowStep,
            @RequestParam(value = "userId", required = false) String userId,
            @RequestParam(value = "topDefault", required = false) String topDefault

    ) {
        Users user = null;
        //解决工作监控代为转交
        user = usersMapper.findUsersByuserId(userId);
        //经办人数组
        String[] alljingbanArray = jingbanUser.split("\\|");
        String[] jingbanArray = null;
        String branchCount = null;
        //用来判断发送事务提醒
        FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);
        //主办人提交消除事物提醒（结束流程时没有主办人）
        //String[] strs1 = flowPrcs.split(",");
        String smsUrl = null;
        if ("2".equals(flowProcess.getTopDefault())) {
            smsUrl = "/workflow/work/workform?opflag=0&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        } else {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        }
        if ("document".equals(tableName)) {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + flowStep + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + currentPrcsId + "&isNomalType=false";
            smsService.updatequerySmsByType("70", user.getUserId(), smsUrl.trim());
        } else if ("budget".equals(tableName)) {
            smsUrl += "&tableName=budget";
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        } else {
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        }
        //获取当前步骤是否需要进行自动归档
        FlowProcess flowPro = wfeFlowProcess.findbyprcsId(flowId, prcsId);
        String autoArchiveSet = flowPro.getAutoArchiveSet();
        if (!StringUtils.checkNull(autoArchiveSet)) {
            String file = JSONArray.parseObject(autoArchiveSet).getString("file");
            String rmsRollRoom = JSONArray.parseObject(autoArchiveSet).getString("rmsRollRoom");
            String rmsRoll = JSONArray.parseObject(autoArchiveSet).getString("rmsRoll");
            String fileRule = JSONArray.parseObject(autoArchiveSet).getString("fileRule");
            String mappingRule = JSONArray.parseObject(autoArchiveSet).getString("mappingRule");
            String fileContent = JSONArray.parseObject(autoArchiveSet).getString("fileContent");
        }
        ;


        return wfeRunner.getWfeFlowRunInfo().saveworks(runId, runName, prcsId, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, tableName, smsContent, smsType, orgadd);

        //return wfeRunner.getWfeFlowRunInfo().savework(runId, runName, flowId, prcsId, prcsFlag, flowStep, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, branchCount);
    }
    @RequestMapping("/Circulate")
    @ResponseBody
    public ToJson<SmsBody> Circulate(String viewUser, String flowId, String prcsId, String flowStep, String runId, String runName) {

        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        String userName = users.getUserName();
        ContextHolder.setConsumerType("xoa" + sqlType);
        SmsBody smsBody = new SmsBody();
        smsBody.setFromId(users.getUserId());
        smsBody.setContent("请查阅我的流程！"+"流水号:" + runId + "，工作名称/文号：" + runName);
//                if(!StringUtils.checkNull(meetingWithBLOBs.getStartTime())){
//                    smsBody.setSendTime(DateFormat.getTime(meetingWithBLOBs.getStartTime()));
//                }
        smsBody.setSendTime(DateFormat.getTime(DateFormat.getCurrentTime()));
        smsBody.setSmsType("7");
        smsBody.setIsAttach("0");


        String toUserId="";
        String[] split = viewUser.split(",");
        List<Users> getManagerId = usersMapper.getUsersByUserIds(split);
        StringBuffer sb = new StringBuffer();
        for (Users u : getManagerId) {
            sb.append(u.getUserId() + ",");
        }
        if(sb!=null){
            toUserId=sb.toString();

        }
        if (StringUtils.checkNull(prcsId)&&StringUtils.checkNull(flowStep)){
            smsBody.setRemindUrl("/workflow/work/workformPreView?flowId="+ flowId +"&runId="+ runId);
        }else {
            smsBody.setRemindUrl("/workflow/work/workformPreView?flowId="+ flowId +"&flowStep="+ flowStep +"&runId="+ runId +"&prcsId="+ prcsId);
        }
        //smsBody.setRemindUrl("/workflow/work/workformPreView?flowId="+ flowId +"&flowStep="+ flowStep +"&runId="+ runId +"&prcsId="+ prcsId);
        String title = userName + "：请查阅我的流程！";
        String context = "主题:" + runName;
        ToJson<SmsBody> smsBodyToJson = smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
        smsBodyToJson.setFlag(0);
        smsBodyToJson.setMsg("ok");

        if (!StringUtils.checkNull(viewUser)) {
            FlowRun flowRun = wfeFlowRun.find(Integer.valueOf(runId));
            //修改传阅人
            flowRun.setViewUser(flowRun.getViewUser() + "," + viewUser);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("runId", flowRun.getRunId());
            map.put("viewUser", flowRun.getViewUser());
            wfeFlowRun.updateState(map);//插入流程表传阅人
            String[] viewUserStr = viewUser.split(",");
            Date date = new Date();
            for (String s : viewUserStr) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(date);
                Map map2 = new HashMap();
                map2.put("runId", flowRun.getRunId());
                map2.put("userId", s);
                map2.put("readDate", "2000-01-01 00:00:00");
                map2.put("createDate", dateStr);
                map2.put("readFlag", 0);
                if (StringUtils.checkNull(prcsId)){
                    prcsId="0";
                }
                if (StringUtils.checkNull(flowStep)){
                    flowStep="0";
                }
                map2.put("prcsId", prcsId);
                map2.put("flowPrcs", flowStep);
                toBeReadMapper.insertFlowRunRead(map2);//插入传阅表
            }
        }
        return smsBodyToJson;

    }
    //流程门户数据获取
    @RequestMapping("/queryCountData")
    @ResponseBody
    public ToJson queryCountData(HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        SimpleDateFormat longSdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        ToJson toJson = new ToJson();
        PageParams pageParams = new PageParams();
        map1.put("userId", users.getUserId());
        pageParams.setPage(1);
        pageParams.setPageSize(5);
        pageParams.setUseFlag(true);
        map1.put("page", pageParams);
        List<FlowRunPrcs> list = wfeFlowRunPrcsMapper.selectObjcet(map1);//待办流程
        map.put("wait",pageParams.getTotal());
        List<FlowRunPrcs> dhuwkjajsn = wfeFlowRunPrcsMapper.selectAll(map1);//所有流程
        map.put("all",pageParams.getTotal());
        toJson.setObject(map);
        toJson.setFlag(0);
        toJson.setMsg("ok");
        return toJson;
    }
    //查询会签人的是否办理完毕，会签人未办理，当前人不能办理完毕
    @RequestMapping("/queryopaddUserOver")
    @ResponseBody
    public ToJson queryopaddUserOver(HttpServletRequest request,FlowRunPrcs flowRunPrcs) {
        return flowRunPrcsService.queryopaddUserOver(request,flowRunPrcs);
    }
    //查看当前流程是否已办结，办理中返回true，已办结显示err
    @RequestMapping("/selectFind")
    @ResponseBody
    public ToJson selectFind(HttpServletRequest request,FlowRunPrcs flowRunPrcs) {

        return wfeRunner.getWfeFlowRunInfo().selectFind(request,flowRunPrcs);

    }
    /**
     * @接口说明: 判断是否在ip范围内
     */
    @RequestMapping("/selectFindIp")
    @ResponseBody
    public JSONObject selectFindIp(HttpServletRequest request,FlowRunPrcs flowRunPrcs,
                                   @RequestParam(value = "runId", required = false) Integer runId,
                                   @RequestParam(value = "flowId", required = false) Integer flowId
    ) {

        //InetAddress currentIp = IpAddr.getCurrentIp();
        //String ip = currentIp.toString().substring(1);
        String ip =IpAddr.getIpAddress(request);//获取ip
      //  String ip =IpAddr.getIpAddr(request);//获取ip
        Map<String, Object> mss = wfeRunner.getWfeFlowRunInfo().fastAdd(runId, flowId, request);//获取当前表单数据
        Object obj=mss.get("obj");
        Map datas = JSONObject.parseObject(JSONObject.toJSONString(obj), Map.class);
        String mj=(String)datas.get("DATA_998");//获取字段id
        //String[] ips={"110.87.35.0-110.87.35.255","172.30.17.0-172.30.17.255"};//允许ip
        String[] ips={"172.30.17.0-172.30.17.24","172.18.82.0-172.18.82.24","10.30.2.0-10.30.2.254"};//允许ip
        String pd="";
        //判断文本内容
        if(mj.equals("不公开")){
            pd="notip";
            for(int i=0;i<ips.length;i++){
                String[] ipStartAndEnd=ips[i].split("-");
                if(IpAddr.isValidRange(ipStartAndEnd[0],ipStartAndEnd[1],ip)||ipStartAndEnd[0].equals(ip)||ipStartAndEnd[1].equals(ip)){
                    pd="";
                    break;
                }
            }
        }
        String retJson="";
        if(pd.equals("notip")){
            retJson= "{\"flag\":true,\"obj\":[],\"object\":\"err\",\"turn\":false,\"ip\":\""+ip+"\"}";
        }else{
            retJson= "{\"pd\":\""+pd+"\",\"ip\":\""+ip+"\"}";
        }
        JSONObject jsonObject1 =JSONObject.parseObject(retJson);
        return jsonObject1;
    }
    /**
     * @接口说明: 挂起和取消挂起接口
     * @日期: 2020/4/24
     * @作者: 张航宁
     */
    @ResponseBody
    @RequestMapping("pendingWork")
    public ToJson pendingWork(HttpServletRequest request,Integer id
            ,Integer runId,String flowPrcs,String currentPrcsId,String flowId, String prcsId,String prcsFlag) {
        return wfeRunner.getWfeFlowRunPrcs().pendingWork(request, id, runId, flowPrcs, currentPrcsId, flowId, prcsId, prcsFlag);
    }
    //办毕和恢复办毕功能
    @ResponseBody
    @RequestMapping("updateFrpByPrcsId")
    public ToJson updateFrpByPrcsId(HttpServletRequest request, Integer id, Integer flag) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        ToJson json = new ToJson();
        FlowRunPrcs flowRunPrcs = new FlowRunPrcs();
        flowRunPrcs.setId(id);
        try {
            if (flag == 0) {//办毕
                Date date = new Date();
                flowRunPrcs.setDeliverTime(longSdf.format(date));
                flowRunPrcs.setPrcsFlag("4");
            } else if (flag == 1) {//恢复办理
                flowRunPrcs.setDeliverTime("2000-01-01 00:00:00");
                flowRunPrcs.setPrcsFlag("2");
            }
            wfeRunner.getWfeFlowRunInfo().updateFrpById(flowRunPrcs);
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    //子流程退回到父流程
    @ResponseBody
    @RequestMapping("returnParentFrp")
    public ToJson returnParentFrp(FlowRunPrcs flowRunPrcs) {
        return wfeFlowRunPrcs.returnParentFrp(flowRunPrcs);
    }

    //删除表单意见
    @ResponseBody
    @RequestMapping("deleteOpinion")
    public ToJson deleteOpinion(HttpServletRequest request,FlowRunPrcs flowRunPrcs) {
        return wfeFlowRun.deleteOpinion(request,flowRunPrcs);
    }
    @RequestMapping(value = "getAssignData", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson<FlowRunPrcs> getAssignData(FlowRunPrcs flowRunPrcs, HttpServletRequest request,
                                      @RequestParam(value = "page", required = false) Integer page,
                                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                      @RequestParam(value = "useFlag", required = false) boolean useFlag

    ) {
        String flowId = request.getParameter("flowId");
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StringUtils.checkNull(flowRunPrcs.getUserId())) {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
            maps.put("userId", userId);
        } else {
            maps.put("userId", flowRunPrcs.getUserId());
        }
        if (!StringUtils.checkNull(flowRunPrcs.getMyworkconditions())) {
            maps.put("myworkconditions", flowRunPrcs.getMyworkconditions());
        }
        if (!StringUtils.checkNull(flowId)) {
            maps.put("flowId", flowId);
        }
        return wfeRunner.getWfeFlowRunPrcs().getAssignData(maps, page, pageSize, useFlag);
    }
    /**
     * 方法介绍: 批量下载附件为zip文件
     */
    @ResponseBody
    @RequestMapping("/downLoadZipAtt")
    public ToJson downLoadZipAttachment(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        return wfeRunner.getWfeFlowRunPrcs().downLoadZipAtt(request,response);
    }
    /**
     *更新frp中的Comment为空
     */
    @ResponseBody
    @RequestMapping("/updateComment")
    public ToJson updateComment(HttpServletRequest request, FlowRunPrcs flowRunPrcs) {
        ToJson json = new ToJson();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Users sessionInfo = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        try {
            Map<String, Object> map = new HashMap();
            map.put("flowPrcs", flowRunPrcs.getPrcsId());
            map.put("prcsId", flowRunPrcs.getFlowPrcs());
            map.put("runId", flowRunPrcs.getRunId());
            map.put("userId", sessionInfo.getUserId());
            List<FlowRunPrcs> allByComment = flowRunPrcsMapper.getAllByComment(map);
            for (FlowRunPrcs frp : allByComment) {
                DocumentModel documentModel = documentSerivce.checkRunId(frp.getRunId());
                String tableName = "";
                String tabId = "";
                if (documentModel != null) {
                    tableName = "document";
                    tabId = String.valueOf(documentModel.getId());
                }
                frp.setComment("");
                int i = flowRunPrcsMapper.updateComment(frp);
                try {//消除事务提醒
                    threadService.addNewworkFastAdd(sessionInfo, frp.getFlowId(), frp.getPrcsId(), String.valueOf(frp.getFlowPrcs()), String.valueOf(frp.getRunId()), tableName, tabId, sqlType);
                } catch (Exception e) {

                }
            }
        } catch (Exception e) {

        }
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }
}
